package com.stone.back.user.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stone.back.user.entity.BfCountry;
import com.stone.back.user.entity.BfUser;
import com.stone.base.dao.BaseDao;
import com.stone.base.entity.Page;

/**
 * 用户管理Dao
 * @author Stone P
 *
 */
@Repository
public class UserDao extends BaseDao implements IUserDao {
	/**
	 * 查询登陆信息
	 * @param email				email
	 * @param password			密码
	 * @return				
	 */
	@Override
	public List<BfUser> userLogin(String email, String password) {
		String hql = "from BfUser where email = ? and password = ? and (type = 0 or type = 2)";
		List<BfUser> list = this.hibernateTemplate.find(hql, email, password);
		return list;
	}
	
	/**
	 * 查询用户分页信息
	 * @param pageNumber						页数
	 * @param userName							用户名
	 * @param email								email
	 * @param sex								性别
	 * @param type(0:普通 1:后台 2：系统管理员)		用户类型
	 * @return
	 */
	@Override
	public Page selectUserPage(int pageNumber, String userName, String email, String sex, String type) {
		StringBuilder hql = new StringBuilder("from BfUser where type != 2 ");
		if(StringUtils.isNotBlank(userName)) {
			hql.append(" and username like '%" + userName + "%'");
		}
		if(StringUtils.isNotBlank(email)) {
			hql.append(" and email like '%" + email + "%'");
		}
		if(StringUtils.isNotBlank(sex)) {
			hql.append(" and sex = " + sex);
		}
		if(StringUtils.isNotBlank(type)) {
			hql.append(" and type = " + type);
		}
		hql.append(" order by userId desc");
 		Page page = this.queryPage(hql.toString(), pageNumber);
		return page;
	}

	/**
	 * 通过登录名查找用户信息
	 * @param email		email
	 * @return
	 */
	@Override
	public List<BfUser> selectUserByEmail(String email) {
		String hql = "from BfUser where email = '" + email + "'";
		List<BfUser> list = this.hibernateTemplate.find(hql);
		return list;
	}
	
	/**
	 * 查询国家列表
	 * @return
	 */
	@Override
    public @ResponseBody List<BfCountry> selectCountry() {
		String hql = "from BfCountry";
		List<BfCountry> list = this.hibernateTemplate.find(hql);
		return list;
	}

	/**
	 * 增加用户
	 * @param user	用户信息
	 * @return
	 */
	@Override
	public Integer addUser(BfUser user) {
		return (Integer) this.hibernateTemplate.save(user);
	}

	/**
	 * 修改用户
	 * @param user	用户信息
	 * @return
	 */
	@Override
	public void updateUser(BfUser user) {
		this.hibernateTemplate.update(user);
	}

	/**
	 * 查询用户详情
	 * @param userId	用户Id
	 * @return
	 */
	@Override
	public BfUser selectUserDetail(int userId) {
		return this.hibernateTemplate.get(BfUser.class, userId);
	}

	/**
	 * 删除用户
	 * @param userId	用户Id
	 * @return
	 */
	@Override
	public void deleteUser(BfUser user) {
		this.hibernateTemplate.delete(user);
	}
}
